from django.http import JsonResponse
from django.shortcuts import render, HttpResponse
from django.shortcuts import redirect
from APP01 import models
from django.views.generic import View
from APP01.models import UserInfo, Cart, Order, OrderGoods, goods_info, Admin
from django.contrib.auth import authenticate, logout
import re
import time
import random
from price_add import get_total_price, get_count_total
import os


# Create your views here.


def index(request):
    return render(request, 'index.html')


#  后台中心页面
def user_info(request):
    admin_list = models.Admin.objects.all()
    return render(request, '后台/user_info.html', {'admin_list': admin_list})


# 用户中心
def User_center(request):
    if request.method == "GET":
        user_list = models.UserInfo.objects.all()
        return render(request, '后台/User_center.html', {'user_list': user_list})
    elif request.method == "POST":
        u = request.POST.get('user')
        p = request.POST.get('pwd')
        models.UserInfo.objects.create(username=u, password=p)
        return redirect('/user_info/')


# 删除操作
def delete(request):
    # 1.获取要删除出版社的ID
    delete_id = request.GET.get('id')
    # 2.根据id去数据库删除对应的数据行
    UserInfo.objects.filter(id=delete_id).delete()

    return redirect('/User_center/')


# 增加用户信息
class Add_userinfoView(View):
    def get(self, request):
        '''显示注册页面'''
        return render(request, 'Add_userinfo.html')

    def post(self, request):
        ''' 进行注册处理 '''
        u = request.POST.get('user')
        p = request.POST.get('pwd')
        e = request.POST.get('email')
        t = request.POST.get('phone')
        n = request.POST.get('number')
        if not all([u, p, e, t, n]):
            return render(request, 'Add_userinfo.html', {'errmsg': '数据不完整'})

            # 校验邮箱
        if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', e):
            return render(request, 'Add_userinfo.html', {'errmsg': '格式错误'})

        obj = models.UserInfo.objects.create(username=u, password=p, email=e, phone=t, number=n)
        if obj:
            return render(request, '后台/User_center.html')


def edit(request):
    if request.method == "GET":
        return render(request, '后台/edit.html')
    edit_id = request.GET.get('id')
    if request.method == "POST":
        # 将信息发到修改页面
        # 去除用户编辑之后的数据
        new_name = request.POST.get('name1')
        new_password = request.POST.get('name2')
        new_email = request.POST.get('name3')
        new_phone = request.POST.get('name4')
        new_number = request.POST.get('name5')
        edit_ps1 = models.UserInfo.objects.get(id=edit_id)
        edit_ps1.username = new_name
        edit_ps1.password = new_password
        edit_ps1.email = new_email
        edit_ps1.phone = new_phone
        edit_ps1.number = new_number
        edit_ps1.save()
        return redirect('/user_info/')
        # 去数据库修改数据
        # 让用户再去访问信息列表
        # 一个对象
    ret = models.UserInfo.objects.get(id=edit_id)
    return render(request, '后台/edit.html', {'edit_info': ret})


# 注册视图类
class RegiterView(View):
    def get(self, request):

        return render(request, '用户登录与注册/Regiter.html')

    def post(self, request):

        u = request.POST.get('user')
        p = request.POST.get('pwd')
        e = request.POST.get('email')
        t = request.POST.get('phone')
        n = request.POST.get('number')
        a = request.POST.get('address')
        token = time.time() + random.randrange(1, 10000000)
        usertoen = str(token)
        try:
            user = UserInfo.objects.get(username=u)
        except UserInfo.DoesNotExist:
            user = None
        if user:
            return render(request, '用户登录与注册/Regiter.html', {'errmsg': '用户名已存在'})

        if not all([u, p, e, t, n]):
            return render(request, '用户登录与注册/Regiter.html', {'errmsg': '数据不完整'})

            # 校验邮箱
        if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', e):
            return render(request, '用户登录与注册/Regiter.html', {'errmsg': '格式错误'})
        # 进行注册
        OBJ = models.UserInfo.objects.create(username=u, password=p, email=e, phone=t, number=n, userAddress=a,
                                             userToken=usertoen)
        if OBJ:
            request.session["username"] = u
            request.session["number"] = n
            request.session["email"] = e
            request.session["useradress"] = a
            request.session["phone"] = t
            return render(request, '商城/Home.html', {'message': '注册成功', })


# 登录类视图
class LoginView(View):
    def get(self, request):
        return render(request, '用户登录与注册/Login2.html')

    def post(self, request):
        u = request.POST.get('username')
        p = request.POST.get('password')
        number = request.POST.get('number')
        email = request.POST.get('email')
        token = request.POST.get('token')

        user_view = UserInfo.objects.filter(username=u, password=p, number=number, email=email)
        if user_view:

            request.session["username"] = u
            request.session["number"] = number
            request.session["email"] = email
            request.session["token"] = token
            return redirect('/Home/', {'user_view': UserInfo})
        else:
            return render(request, '用户登录与注册/Login2.html', {'errmsg': '用户名或者密码错误'})


# 退出登录
def quite(request):
    logout(request)
    return redirect('/Home/')


# 主页
def Home(request):
    obj = goods_info.objects.all()
    username = request.session.get("username", "未登录")
    token = request.session.get("token")
    return render(request, '商城/Home.html', {"obj": obj, "username": username, "token": token})


# 商品图片
def image(request):
    if request.method == "GET":
        return render(request, '后台/image.html')
    if request.method == 'POST':
        img = request.FILES.get('img')
        n = request.POST.get('name')
        p = request.POST.get('price')
        q = request.POST.get('info')
        obj = models.goods_info.objects.create(img=img, goods_name=n, goods_price=p, goods_info=q)
        if obj:
            return render(request, '后台/image.html')


def show(request):
    obj = models.goods_info.objects.all()
    return render(request, 'show.html', {'img': obj})


# 管理员
def Admin_INFO(request):
    if request.method == "GET":
        return render(request, '后台/Admin.html')
    if request.method == "POST":

        user = request.POST.get('username')
        pwd = request.POST.get('password')
        obj = models.Admin.objects.filter(username=user, password=pwd)
        if obj:
            return render(request, '后台/user_info.html', {'user_list': obj})


# 修改购物车
def addcart(request):
    goodsid = request.GET.get('goodsid')
    carts = Cart.objects.filter(c_user=request.user).filter(c_goods_id=goodsid)
    if carts.exists():
        carts_obj = carts.first()
        carts_obj.c_goods_num = carts_obj.c_goods_num + 1
    else:
        carts_obj = Cart()
        carts_obj.c_goods_id = goodsid
        carts_obj.c_user = request.user
    carts_obj.save()
    data = {
        'status': 200,
        'message': 'add succes',
        'num': carts_obj.c_goods_num
    }
    return JsonResponse(data=data)


# 用户信息
def person(request):
    info = UserInfo.objects.all()
    username = request.session.get("username")
    number = request.session.get("number")
    email = request.session.get("email")
    useradress = request.session.get("useradress")
    phone = request.session.get("phone")
    return render(request, '个人信息/person_info.html',
                  {"username": username, "number": number, "email": email, 'info': info, "useradress": useradress,
                   "phone": phone})


# 购物车
def user_cart(request):
    username1 = request.session.get("username", "未登录")
    carts = Cart.objects.filter(c_user=request.user)
    is_all_select = not carts.filter(c_is_select=False).exists()
    data = {
        'title': '购物车',
        'carts': carts,
        'username': username1,
        'total_price': get_total_price(),
        'count_add': get_count_total(),
        'c_is_select': is_all_select
    }
    return render(request, '商城/cart.html', context=data)


# 修改购物车
def Changecarts(request):
    # 查找
    cart_id = request.GET.get('cartsid')
    # 风险 cart_id可能不是自己的  所以需要判别是否是自己的购物
    cart_obj = Cart.objects.get(c_goods__cart=cart_id)
    cart_obj.c_is_select = not cart_obj.c_is_select
    is_all_select = not Cart.objects.filter(c_user=request.user).filter(c_is_select=False).exists()
    data = {
        'status': 200,
        'msg': 'change ok',
        'c_is_select': cart_obj.c_is_select,
        'is_all_select': is_all_select
    }
    cart_obj.save()
    return JsonResponse(data=data)


# 减少购物车数量
def subshoppings(request):
    carid = request.GET.get('cartsid')

    cart_obj = Cart.objects.get(c_goods__cart=carid)
    data = {

        'status': 200,
        'message': 'ok',
        'total_price': get_total_price()
    }
    if cart_obj.c_goods_num > 1:
        cart_obj.c_goods_num = cart_obj.c_goods_num - 1
        cart_obj.save()
        data['c_goods_num'] = cart_obj.c_goods_num
    else:
        cart_obj.delete()
        data['c_goods_num'] = 0
    return JsonResponse(data=data)


# 增加购物车数量
def addshoppings(request):
    carid = request.GET.get('cartsid')

    cart_obj = Cart.objects.get(c_goods__cart=carid)
    data = {

        'status': 200,
        'message': 'ok',
        'total_price': get_total_price()
    }
    if cart_obj.c_goods_num < 10:
        cart_obj.c_goods_num = cart_obj.c_goods_num + 1
        cart_obj.save()
        data['c_goods_num'] = cart_obj.c_goods_num
    else:
        return render(request, '商城/cart.html', {"meg": "无库存"})


def allselect(request):
    cart_list = request.GET.get('cart_list')

    carts = Cart.objects.filter(c_goods__cart__in=cart_list)
    for cart_obj in carts:
        cart_obj.c_is_select = not cart_obj.c_is_select
        cart_obj.save()
    data = {
        'status': 200,
        'msg': 'ok'
    }
    return JsonResponse(data=data)


# 支付与购物车表关联
def pay(request):
    carts = Cart.objects.filter(c_user=request.user).filter(c_is_select=True)
    order = Order()
    order.o_user = request.user
    order.o_price = get_total_price()
    order.save()

    for cart_obj in carts:
        ordergoods = OrderGoods()
        ordergoods.o_order = order
        ordergoods.o_goods_num = cart_obj.c_goods_num
        ordergoods.o_goods = cart_obj.c_goods
        ordergoods.save()
        cart_obj.delete()

    data = {
        'status': 200,
        'meg': 'ok',
        'order_id': order.id
    }
    return JsonResponse(data=data)


# 订单
def order(request):
    order_id = request.GET.get('orderid')
    order = Order.objects.get(o_user__cart=order_id)
    data = {
        'title': '订单',
        'order': order
    }
    return render(request, '商城/order.html', context=data)
